package Scene

import (
	. "GameLogic/GameConfig"
	"PBMessage"
	. "SGNet"
	proto "github.com/golang/protobuf/proto"
	"misc/NavMesh"
)

type Scene struct {
	//单位字典
	units map[string]IUnit
	//触发器
	Trigger ISceneTrigger
	//所有玩家
	GamePlayers []*GamePlayer
	//导航网格
	NavMesh *NavMesh.NavMesh
}

func NewScene() *Scene {
	retScene := &Scene{
		units:       make(map[string]IUnit),
		GamePlayers: make([]*GamePlayer, 0),
	}
	retScene.Trigger = newSceneTrigger(retScene)
	return retScene
}

func (scene *Scene) Init() {
	scene.NavMesh = &NavMesh.NavMesh{}
	scene.NavMesh.LoadNavMesh("..\\..\\Public\\NavMesh\\DemoNav.Data")
	scene.Trigger.Init()
}

func (scene *Scene) OnLoad() {
	scene.Trigger.OnLoad()
}

func (scene *Scene) Update() {
	scene.Trigger.Update()
	for _, unit := range scene.units {
		unit.Update()
	}
}

func (scene *Scene) SetSceneTrigger(trigger ISceneTrigger) {
	scene.Trigger = trigger
}

func (scene *Scene) CreateUnit(unitName string, gamePlayerId int, uuid string) IUnit {
	xmlUnit := GetXmlUnit(unitName)
	newUnit := CreateUnit(xmlUnit, uuid, gamePlayerId, scene)
	scene.AddUnit(newUnit)
	return newUnit
}

func (scene *Scene) AddUnit(unit IUnit) {
	scene.units[unit.GetBaseUnit().UUID] = unit
	unit.OnEnter()
}

func (scene *Scene) GetUnit(uuid string) IUnit {
	return scene.units[uuid]
}

func (scene *Scene) AddGamePlayer(player *GamePlayer) {
	scene.GamePlayers = append(scene.GamePlayers, player)
}

func (scene *Scene) SendToAllPlayer(msgid int, msg proto.Message) {
	for i := 0; i < len(scene.GamePlayers); i++ {
		scene.GamePlayers[i].Sess.SendPacket(msgid, msg)
	}
}

func (scene *Scene) HandlerPushUnitCommand(msg *Message) {
	PushCmdMsg := &PBMessage.CS_PushUnitCommand{}
	proto.Unmarshal(msg.Data, PushCmdMsg)
	unit := scene.GetUnit(PushCmdMsg.GetUnitID())
	unit.PushCmd(PushCmdMsg.GetCmdId(), PushCmdMsg.GetPushType(), PushCmdMsg.GetInts(), PushCmdMsg.GetFloats(), PushCmdMsg.GetStrs())
}

func (scene *Scene) GamePlayerLost(userKey string) {
	for i := 0; i < len(scene.GamePlayers); i++ {
		if scene.GamePlayers[i] != nil && scene.GamePlayers[i].UserName == userKey {
			scene.GamePlayers[i] = nil
		}
	}
}
